package com.polaris.live.viewmodel.luckybag

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.polaris.live.common.constant.CommonConst
import com.polaris.live.common.manager.startCountdown
import com.polaris.live.common.mvvm.viewmodel.BaseViewModel
import com.polaris.live.common.mvvm.viewmodel.SequentialLiveData
import com.polaris.live.common.network.ApiResponse
import com.polaris.live.common.network.request
import com.polaris.live.common.network.requestLoading
import com.polaris.live.common.network.requestNoCheck
import com.polaris.live.common.network.state.ResultState
import com.polaris.live.common.util.JsonUtils
import com.polaris.live.im.sfs.bean.pusher.LuckyBagNoticeMessage
import com.polaris.live.net.chatService
import com.polaris.live.resp.back_resp.luckybag.LuckyBagDetailResp
import com.polaris.live.resp.back_resp.luckybag.LuckyBagMessageResp
import com.polaris.live.resp.base.ListResp
import com.polaris.live.resp.go_resp.luckybag.LuckyBagReceiveBean
import com.polaris.live.resp.go_resp.luckybag.LuckyBagSendChatBean
import com.polaris.live.viewmodel.message.MessageSessionViewModel
import kotlinx.coroutines.launch

/**
 * LuckyBagViewModel
 *
 * @author Created by lucas on 2024/6/11 02:13
 * @since 1.0.0
 */
class LuckyBagViewModel : BaseViewModel() {

    var mLiveId: Long? = null
    var mOnlyUncompleted: Boolean = false
    var mPageIndex = 0
    var mOnlyMessage: Boolean? = null

    val mListLiveData = MutableLiveData<ResultState<ListResp<LuckyBagMessageResp>>>()

    fun onRefresh() {
        mPageIndex = 0

        loadData()
    }

    fun onLoadMore() {
        mPageIndex++

        loadData()
    }

    private fun loadData() {
        request({ chatService.getLuckyBagMessages(mLiveId, mOnlyUncompleted, mPageIndex, mOnlyMessage) }, mListLiveData)
    }

    //开始观察页面消息
    fun startObserveState() {
        viewModelScope.startCountdown(Long.MAX_VALUE, 25 * 1000L, {
            chatService.observeUserState()
        })
    }

    //处理通知的消息
    val mNoticeMessageLiveData = SequentialLiveData<LuckyBagMessageResp>()
    fun resolveNoticeMessage(message: LuckyBagNoticeMessage) {
        viewModelScope.launch {
            //发送的消息里面只有id，这里需要重新获取下信息
            val (content, sendBean) = if (message.messageType == CommonConst.LuckyBagMessageType.LUCKY_BAG) {
                val sendSimple = JsonUtils.fromJson<LuckyBagNoticeMessage.LuckyBagMessageSendSimple>(message.content)

                sendSimple?.let {
                    val userBasic = MessageSessionViewModel.getUserBasicVo(it.userId)
                    userBasic?.let { user ->
                        //这里的消息一定会是未领取的
                        val sendBean = LuckyBagMessageResp.LuckyBagMessageSend(
                            user,
                            it.coins,
                            0,
                            it.bombNum,
                            CommonConst.LuckyBagStatus.RECEIVING
                        )

                        JsonUtils.toJson(sendBean) to sendBean
                    }
                } ?: (null to null)
            } else {
                message.content to null
            }
            if (content == null) {
                return@launch
            }

            val resp = LuckyBagMessageResp(
                message.messageId,
                message.luckyBagId,
                message.userId,
                message.messageType,
                content,
                message.createTime
            ).apply {
                sendBean?.also {
                    updateBagMessage(it)
                }
            }

            mNoticeMessageLiveData.setValue(resp)
        }
    }

    //领取福袋
    val mReceiveLiveData = MutableLiveData<LuckyBagReceiveBean>()
    fun receiveLuckyBag(luckyBagId: Long, coins: Long) {
        requestNoCheck({ chatService.receiveLuckyBag(LuckyBagReceiveBean(luckyBagId, mLiveId)) }, {
            mReceiveLiveData.value = LuckyBagReceiveBean(luckyBagId, coins, it)
        })
    }

    //查看福袋详情
    val mDetailLuckyBagLiveData = MutableLiveData<ResultState<LuckyBagDetailResp>>()
    fun gotoDetailLuckyBag(luckyBagId: Long) {
        requestLoading({ chatService.luckyBagDetail(luckyBagId) }, mDetailLuckyBagLiveData)
    }

    //发送福袋聊天消息
    fun sendLuckyBagChat(content: String) {
        requestLoading({ chatService.sendLuckyBagChat(LuckyBagSendChatBean(content)) }, {})
    }

    class LuckyBagReceiveBean(
        val luckyBagId: Long,
        val coins: Long,
        val resp: ApiResponse<LuckyBagDetailResp>,
    )
}